package pe.com.ValoracionVivienda.security;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

public class AESEncryption {

	private final static String KEY = "KEY10T3S1S2014-2"; // 128 bit key
	
	public static String descifrar(String text) throws DecoderException, NoSuchAlgorithmException, NoSuchPaddingException
		,InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		
		byte[] bytes = Hex.decodeHex(text.toCharArray());
		Key aesKey = new SecretKeySpec(KEY.getBytes(), 0, 16, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, aesKey);
		
		return new String(cipher.doFinal(bytes));
	}
	
	public static String cifrar(String text) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException
		, IllegalBlockSizeException, BadPaddingException{
		
		Key aesKey = new SecretKeySpec(KEY.getBytes(), 0, 16, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		
		cipher.init(Cipher.ENCRYPT_MODE, aesKey);
		byte[] encrypted = cipher.doFinal(text.getBytes());
		return Hex.encodeHexString(encrypted);
	}
}
